import sys
from PySide6.QtWidgets import QWidget,QVBoxLayout,QPlainTextEdit,QScrollBar
from PySide6.QtCore import  Qt, QFileSystemWatcher
import os
import itertools


class LogWidget(QWidget):
    line_number = 0
    file_size = 0

    def __init__(self, main_ui):
        super().__init__()
        self.main_ui = main_ui
        self.log_path = main_ui.log_path
        self.log_dir = main_ui.log_dir
        self.config = main_ui.config
        # self.line_number = main_ui.line_number
        # self.file_size = main_ui.file_size
        self.tab_info_layout = QVBoxLayout(self)
        self.text_plain_info = QPlainTextEdit(self)
        self.text_plain_info.resize(800, 450)

        self.text_plain_info.setReadOnly(True)
        self.text_plain_info.setUndoRedoEnabled(False)
        self.text_plain_info.setMaximumBlockCount(800)
        scrolbar = QScrollBar(self)
        self.text_plain_info.setVerticalScrollBar(scrolbar)
        self.text_plain_info.setVerticalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOn
        )
        self.line_number = self.get_file_line_count(main_ui.log_path)
        self.file_size=self.get_file_size(main_ui.log_path)
        self.watcher = QFileSystemWatcher()
        self.watcher.addPath(self.log_path)
        self.watcher.addPath(self.log_dir)
        self.watcher.fileChanged.connect(self.file_changed)
        self.watcher.directoryChanged.connect(self.directory_changed)
        self.tab_info_layout.addWidget(self.text_plain_info)
        self.setLayout(self.tab_info_layout)

    def directory_changed(self, str):
        # print(f"{str}目录变化")
        result = self.watcher.files()
        if len(result) == 0:
            self.watcher.addPath(self.log_path)
            # self.watcher.fileChanged.connect(self.file_changed)

    def file_changed(self):
        # print(self.log_path)
        sz = self.get_file_size(self.log_path)
        # print(f"self.file_size:{self.file_size}")
        # print(f"size:{sz}")
        if sz is not None and sz < self.file_size:
            self.line_number = 0
        lines = self.read_specific_lines(str_path=self.log_path)
        # print(lines)
        self.line_number = self.line_number + len(lines)
        self.file_size = sz
        for line in lines:
            self.text_plain_info.appendPlainText(line.strip())

    def read_specific_lines(self, str_path):
        with open(file=str_path, mode="r", encoding="utf-8") as file:
            # 从起始行一直读到末尾
            return list(itertools.islice(file, self.line_number, None, None))

    def get_file_line_count(self, file_path):
        with open(file_path, "r", encoding="utf-8") as file:
            lines_count = sum(1 for line in file)
            return lines_count

    def get_file_size(self, file_path):
        if os.path.isfile(file_path):
            # 获取文件大小（字节）
            file_size = os.path.getsize(file_path)
            return file_size
        else:
            return 0


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     widget = RedisWidget(main_ui=myMainWindow())
#     widget.resize(800, 600)
#     widget.show()
#     sys.exit(app.exec())
